const path = require("path");
const Router = require("koa-router");
const { koaBody } = require("koa-body");

const {
  userValidator,
  verifyLogin,
  verifyUser,
  cryptPassword,
  addUserValidator,
} = require("../../middleware/admin/user.middleware");
const {
  auth,
  hadAdminPermission,
} = require("../../middleware/admin/auth.middleware");
const {
  register,
  login,
  changePassword,
  upload,
  addUser,
  findAll,
  remove,
  findOne,
  update,
} = require("../../controllers/admin/user.controller");

const router = new Router({ prefix: "/adminapi" });

//添加用户接口
router.post(
  "/user/add",
  koaBody({
    multipart: true,
    formidable: {
      //配置选项option，不推荐使用相对路径
      //在option里的相对路径，不是相对的当前文件，相对于process.cwd
      uploadDir: path.join(__dirname, "../../public/avataruploads"),
      keepExtensions: true,
    },
  }),
  // addUserValidator,  //验证前端传来数据的合法性先由前端控制
  cryptPassword,
  addUser
);
//登录接口
router.post("/user/login", userValidator, verifyLogin, login);

//修改密码接口
router.patch("/", auth, cryptPassword, changePassword);

// /adminapi/user/upload
router.post(
  "/user/upload",
  auth,
  cryptPassword,
  koaBody({
    multipart: true,
    formidable: {
      //配置选项option，不推荐使用相对路径
      //在option里的相对路径，不是相对的当前文件，相对于process.cwd
      uploadDir: path.join(__dirname, "../../public/avataruploads"),
      keepExtensions: true,
    },
  }),
  upload
);

//获取用户列表
router.get("/user/list", findAll);
//获取单个用户信息
router.get("/user/list/:id", findOne);

//修改用户信息
router.put("/user/list/:id", auth, hadAdminPermission, cryptPassword, update);

//删除用户
router.delete("/user/list/:id", auth, hadAdminPermission, remove);

// 测试接口;
// router.post("/user/upload", (ctx) => {
//   ctx.body = "hello world";
// });

module.exports = router;
